﻿using System;
using System.Collections.Generic;
using Alserve.Ffl;
using Alserve.Ffl.Data;

public partial class ffl_anonymous_premierleaguetable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PremierLeagueTableRepeater.DataSource = UpdatePremierLeagueTable();
            PremierLeagueTableRepeater.DataBind();
        }
    }

    private List<LeagueTableItem> UpdatePremierLeagueTable()
    {
        List<LeagueTableItem> returnValue = new List<LeagueTableItem>();

        Club thisClub = new Club();

        if (thisClub.LoadAll())
        {
            while(!thisClub.EOF)
            {
                LeagueTableItem thisLeagueTableItem = new LeagueTableItem();
                thisLeagueTableItem.ClubId = thisClub.Id;
                thisLeagueTableItem.ClubName = thisClub.ClubName;
                thisLeagueTableItem.LeaguePosition = thisClub.Id;
                returnValue.Add(thisLeagueTableItem);

                thisClub.MoveNext();
            }
        }

        Match thisMatch = new Match();
        thisMatch.Where.CompetitionId.Value = 1;

        if (thisMatch.Query.Load())
        {
            while (!thisMatch.EOF)
            {
                LeagueTableItem homeLeagueTableItem = returnValue.Find(r => r.ClubId == thisMatch.HomeClubId);
                LeagueTableItem awayLeagueTableItem = returnValue.Find(r => r.ClubId == thisMatch.AwayClubId);

                if (thisMatch.HomeClubGoals > thisMatch.AwayClubGoals)
                {
                    homeLeagueTableItem.HomeWon++;
                    homeLeagueTableItem.Points += 3;
                    awayLeagueTableItem.AwayLost++;
                }

                if (thisMatch.HomeClubGoals < thisMatch.AwayClubGoals)
                {
                    awayLeagueTableItem.AwayWon++;
                    awayLeagueTableItem.Points += 3;
                    homeLeagueTableItem.HomeLost++;
                }

                if (thisMatch.HomeClubGoals == thisMatch.AwayClubGoals)
                {
                    homeLeagueTableItem.HomeDrawn++;
                    homeLeagueTableItem.Points++;
                    awayLeagueTableItem.AwayDrawn++;
                    awayLeagueTableItem.Points++;
                }

                

                homeLeagueTableItem.HomeGoalsFor += thisMatch.HomeClubGoals;
                homeLeagueTableItem.HomeGoalsAgainst += thisMatch.AwayClubGoals;
                awayLeagueTableItem.AwayGoalsFor += thisMatch.AwayClubGoals;
                awayLeagueTableItem.AwayGoalsAgainst += thisMatch.HomeClubGoals;

                homeLeagueTableItem.HomePlayed++;
                awayLeagueTableItem.AwayPlayed++;

                thisMatch.MoveNext();
            }
        }

        returnValue.Sort();
        return returnValue;
    }

}
